package com.yuyang.gulimall.coupon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuyang.gulimall.coupon.entity.SeckillSkuRelationEntity;
import com.yuyang.gulimall.coupon.service.SeckillSkuRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuyang.common.utils.PageUtils;
import com.yuyang.common.utils.Query;

import com.yuyang.gulimall.coupon.dao.SeckillSessionDao;
import com.yuyang.gulimall.coupon.entity.SeckillSessionEntity;
import com.yuyang.gulimall.coupon.service.SeckillSessionService;


@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {
    @Autowired
    SeckillSkuRelationService seckillSkuRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSessionEntity> page = this.page(
                new Query<SeckillSessionEntity>().getPage(params),
                new QueryWrapper<SeckillSessionEntity>()
        );

        return new PageUtils(page);
    }
    //上架最近三日的秒杀商品
    @Override
    public List<SeckillSessionEntity> uploadSeckillSkuLatest3Days() {
        LocalDate now = LocalDate.now();
        String start_time = LocalDateTime.of(now, LocalTime.MIN).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String end_time = LocalDateTime.of(now.plusDays(2), LocalTime.MAX).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        LambdaQueryWrapper<SeckillSessionEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.between(SeckillSessionEntity::getStartTime,start_time,end_time);
        List<SeckillSessionEntity> list = this.list(lambdaQueryWrapper);

        return list.stream().peek(seckillSessionEntity -> {
            Long id = seckillSessionEntity.getId();
            List<SeckillSkuRelationEntity> skuRelationEntities = seckillSkuRelationService.list(new LambdaQueryWrapper<SeckillSkuRelationEntity>().eq(SeckillSkuRelationEntity::getPromotionSessionId, id));
            seckillSessionEntity.setRelationSkus(skuRelationEntities);
        }).collect(Collectors.toList());
    }

}